define(['jquery', 'bootstrap', 'backend','table', 'form','upyun','select2','summernote'], function ($, undefined, Backend,Table, Form,UpYun,Select2,Summernote) {

    var Controller = {
        index: function () {
            $(document).on('click', '.thisaddtabs', function (e) {
                Backend.api.addtabs(Backend.api.replaceids(this, $(this).attr('url')), $(this).attr('title'));
                return false;
            });

            $(document).on('click', '#chkSelectAll', function (e) {
                var c = $(this).attr("checked");
                //console.log(c);
                if(typeof(c)=='undefined'){
                    $(this).attr("checked","");
                }else{
                    $(this).removeAttr("checked");
                }
                $("#table input[name=btSelectItem]").each(function(){
                    $(this).prop("checked",!$(this).prop("checked"));
                });
                if($("input[name=btSelectItem]:checked").length>0){
                    $(".btn-del").removeClass('disabled');
                }else{
                    $(".btn-del").addClass('disabled');
                }
                return false;
            });

            $(document).on('click', 'input[name=btSelectItem]',function (e) {  
                if($("input[name=btSelectItem]:checked").length>0){
                    $(".btn-edit").removeClass('disabled');
                    $(".btn-del").removeClass('disabled');
                    if(typeof($(".btn-more"))!='undefined'){
                        $(".btn-more").removeClass('disabled');
                    }
                }else{
                    $(".btn-edit").addClass('disabled');
                    $(".btn-del").addClass('disabled');
                    if(typeof($(".btn-more"))!='undefined'){
                        $(".btn-more").addClass('disabled');
                    }
                }
            });

            var form = $("form.form-commonsearch");
            if ($(".datetimepicker", form).size() > 0) {
                require(['bootstrap-datetimepicker'], function () {
                    var options = {
                        format: 'YYYY-MM-DD',
                        icons: {
                            time: 'fa fa-clock-o',
                            date: 'fa fa-calendar',
                            up: 'fa fa-chevron-up',
                            down: 'fa fa-chevron-down',
                            previous: 'fa fa-chevron-left',
                            next: 'fa fa-chevron-right',
                            today: 'fa fa-history',
                            clear: 'fa fa-trash',
                            close: 'fa fa-remove'
                        },
                        showTodayButton: true,
                        showClose: true
                    };
                    $('.datetimepicker', form).parent().css('position', 'relative');
                    $('.datetimepicker', form).datetimepicker(options);
                });
            }
            $(".data-select",form).on('change', function (e) {
                var url = $(this).attr("data-url");var s = $(this).attr("data-select");
                $.ajax({
                    type: "post",
                    url: url,
                    data: {pid:$(this).val(),r:Math.random()},
                    dataType: 'JSON',
                    success: function (data, status) {
                        var str = '';
                        $.each(eval(data), function (k, v) {
                            str += '<option value="' + v.id + '">' + v.name + '</option>';
                        });
                        $("#"+s).html(str);
                    },
                    error: function () {
                        alert('编辑失败');
                    },
                    complete: function () {
                        
                    }
                });
            });
            $('div.keep-open ul li[role="menuitem"] input[type="checkbox"]').on('change', function(e){
                var cn = $(this).attr("data-field");
                var cnc = Fast.api.ucfirst(cn);
                if($(this).is(':checked')){
                    if($("#table thead").is(":hidden")){
                        addColumnMobile(cn);
                    }else{
                        addColumnPc(cn);
                    }
                }else{
                    if($("#table thead").is(":hidden")){
                        $("#datalist .card-view[columnname="+cn+"]").remove();
                        $("#table thead tr th[data-field='"+cn+"']").remove();
                    }else{
                        //隐藏那个列
                        $("#datalist tr td[columnname="+cnc+"]").remove();
                        $("#table thead tr th[data-field='"+cn+"']").remove();
                    }
                }
            });
            
            //删除按钮
            $(".btn-del").on("click",function (e) {
                e.preventDefault();
                var chenked = $("input[name='btSelectItem']:checked");
                var ids = "";
                for(var i=0;i<chenked.length;i++){
                    ids += chenked[i].value+",";
                }
                if(chenked.length==0){
                    var index2 = Layer.confirm('请选择模块','请选择');

                }else{
                    var id = $(this).data("id");
                    var that = this;
                    var index = Layer.confirm(
                        __('Are you sure you want to delete this item?'),
                        {icon: 3, title: __('Warning'), shadeClose: true},
                        function () {
                            //http://demo.fastadmin.net/admin/auth/admin/del/ids/247,246,245
                            $.ajax({
                                type: "post",
                                url: "/cms.php/module/dels.html",
                                data: {ids:ids},
                                dataType: 'JSON',
                                success: function (data, status) {
                                    if (status == "success") {
                                        Layer.close(index);
                                        location.reload();
                                    }
                                },
                                error: function () {
                                    alert('编辑失败');
                                },
                                complete: function () {

                                }

                            });

                        }
                    );
                }

            });
            $(".btn-delone").on("click",function(e){
                var ids = $(this).prop("title");
                var index = Layer.confirm(
                    __('Are you sure you want to delete this item?'),
                    {icon: 3, title: __('Warning'), shadeClose: true},
                    function () {
                        $.ajax({
                            type: "post",
                            url: "/cms.php/module/del.html",
                            data: {ids:ids},
                            dataType: 'JSON',
                            success: function (data, status) {
                                if (status == "success") {
                                    Layer.close(index);
                                    location.reload();
                                }
                            },
                            error: function () {
                                alert('编辑失败');
                            },
                            complete: function () {

                            }
                        });
                    }
                );
            });
            //表格切换
            $("#toggleview").on('click', function (e) {
                if($("#table thead").is(":hidden")){
                    //转换table视图
                    $("#table thead").show();
                    var ss = '';
                    $("#datalist tr").each(function(i){
                        var obj = $(this);
                        ss += '<tr data-index="'+i+'">';
                            $.each(eval(pagedata.columns),function(k,v){
                                if(v.isshowlist==1){
                                    switch(k.toLowerCase()){
                                        case 'itemid':
                                            ss += '<td class="bs-checkbox" columnname="'+v.columnenname+'">';
                                            ss += '<input data-index="'+i+'" name="btSelectItem" type="checkbox" value="'+obj.find("div.card-view [columnname='"+k.toLowerCase()+"'] input[type='checkbox']").val()+'" />';
                                        break;
                                        default:
                                            var s4 = obj.find("div.card-view[columnname='"+v.columnenname+"'] span.value").html();
                                            if(typeof(s4)!='undefined'){
                                                ss += '<td columnname="'+k+'">';
                                                ss += s4;
                                            }
                                    }
                                    ss += '</td>';
                                }
                            });
                            ss += '<td columnname="caozuo">';
                                ss += obj.find("div.card-view[columnname='caozuo'] span.value").html();
                            ss += '</td>';
                        ss += '</tr>';
                    });
                    $("#datalist").html(ss);
                }else{
                    //转换cardview视图
                    $("#table thead").hide();
                    var ss = '';
                    $("#datalist tr").each(function(i){
                        var obj = $(this);
                        ss += '<tr data-index="0">';
                        ss += '<td>';
                            ss += '<div class="card-views">';
                            $.each(eval(pagedata.columns),function(k,v){
                                if(v.isshowlist==1){
                                    ss += '<div class="card-view" columnname="'+v.columnenname+'">';
                                    switch(k.toLowerCase()){
                                        case 'itemid':
                                            ss += '<input data-index="'+i+'" name="btSelectItem" type="checkbox" value="'+obj.find("td[columnname='"+k.toLowerCase()+"'] input[type='checkbox']").val()+'" />';
                                        break;
                                        default:
                                            var s4 = obj.find("td[columnname='"+k+"']").html();
                                            if(typeof(s4)!='undefined'){
                                                ss += '<span class="title">'+v.columnname+'</span><span class="value">'+s4+'</span>';
                                            }
                                    }
                                    ss += '</div>';
                                }
                            });
                            ss += '<div class="card-view" columnname="caozuo">';
                                ss += '<span class="title" style="text-align: center; vertical-align: middle; ">操作</span>';
                                ss += '<span class="value">'+obj.find("td[columnname='caozuo']").html()+'</span>';
                              //<span class="value"><a href="/admin/auth/adminlog/detail/ids/1355" class="btn btn-info btn-xs btn-detail btn-dialog" title="详情"><i class="fa fa-list"></i> 详情</a> <a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title=""><i class="fa fa-trash"></i></a></span>
                            ss += '</div>';
                            ss += '</div>';
                        ss += '</td>';
                        ss += '</tr>';
                    });
                    $("#datalist").html(ss);
                }
            });
            //窗体太窄，自动缩小。
            if($(window).width()<768){
                $("#toggleview").trigger('click');
            }
            $(window).resize(function(){
                if($(window).width()<=768){
                    if(!$("#table thead").is(":hidden")){
                      $("#toggleview").trigger('click');
                    }
                }
                if($(window).width()>768){
                    if($("#table thead").is(":hidden")){
                      $("#toggleview").trigger('click');
                    }
                }
            });
            Controller.api.bindevent();
        },

        getindex: function (){
            var ss = '';
            $.ajax({
                type: "get",
                url: 'http://www.andiff.net/index/module/getlist?title=&r='+Math.random(),
                async: 'false',
                dataType: 'jsonp',
                jsonp: 'result',
                success: function (data) {
                    var str = '';
                    $.each(eval(data), function (k, v) {
                        str += '<tr data-index="' + k + '">';
                        str += '<td columnname="Name">'+v.name+'</td>';
                        str += '<td columnname="Enname">'+v.enname+'</td>';
                        //str += '<td columnname="Catname">'+v.catname+'{$vo.catname}</td>';
                        str += '<td columnname="Dir">'+v.dir+'</td>';
                        str += '<td columnname="Createtime">'+v.createdate+'</td>';
                        str += '<td columnname="Updatetime">'+v.updatedate+'</td>';
                        str += '<td columnname="caozuo">';
                        str += '<a href="/cms.php/modulestock/info?ids='+v.itemid+'&name='+v.name+'&enname='+v.enname+'&dir='+v.dir+'" class="btn btn-xs btn-success btn-editone" title="">详细</a></td>';
                        str += '</tr>';
                    });
                    $("#datamodulelist").html(str);
                },
                error: function () {
                    //alert('编辑失败');
                },
                complete: function () {

                }
            });
        },
        add: function () {
          var first = []; /* 省，直辖市 */
          var second = []; /* 市 */
          var third = []; /* 镇 */
          $("#upyun_upload").bind('change',function(){
                UpYun.uploadByAjax('upyun_upload','c-filepath','andiffnet/modulefile');
          });
          $("#upyun_upload1").bind('change',function(){
                UpYun.uploadByAjax('upyun_upload1','c-sqlpath','andiffnet/modulefile');
          });

          Controller.api.bindevent();
        },
        edit: function () {
            $("#upyun_upload").bind('change',function(){
                  UpYun.uploadByAjax('upyun_upload','c-filepath','andiffnet/modulefile');
            });
            $("#upyun_upload1").bind('change',function(){
                  UpYun.uploadByAjax('upyun_upload1','c-sqlpath','andiffnet/modulefile');
            });
            $("#mjs").click(function(){
                var sname = $("#c-enname").val();
                $.ajax({
                    type: "get",
                    url: "/cms.php/module/makejstemplate.html",
                    data: {name:sname},
                    success: function (datas) {
                        Layer.alert('生成完毕');
                    },
                    error: function () {
                        Layer.alert('生成失败');
                    },
                    complete: function () {

                    }
                });
            });
            //生成编辑模板
            $("#mbt").click(function(){
                var sname = $("#c-enname").val();
                $.ajax({
                    type: "get",
                    url: "/cms.php/module/makebjtemplate.html",
                    data: {name:sname},
                    success: function (datas) {
                        Layer.alert('生成完毕');
                    },
                    error: function () {
                        Layer.alert('生成失败');
                    },
                    complete: function () {

                    }
                });
            });
            $("#mlt").click(function(){
                var sname = $("#c-enname").val();
                $.ajax({
                    type: "get",
                    url: "/cms.php/module/makelisttemplate.html",
                    data: {name:sname},
                    success: function (datas) {
                        Layer.alert('生成完毕');
                    },
                    error: function () {
                        Layer.alert('生成失败');
                    },
                    complete: function () {

                    }
                });
            });
            //生成列缓存
            $("#mcc").click(function(){
                var sname = $("#c-enname").val();
                $.ajax({
                    type: "get",
                    url: "/cms.php/column/makefile.html",
                    data: {name:sname},
                    success: function (datas) {
                        Layer.alert('生成完毕');
                    },
                    error: function () {
                        Layer.alert('生成失败');
                    },
                    complete: function () {

                    }
                });
            });
            //生成控制器
            $("#mccon").click(function(){
                var sname = $("#c-enname").val();
                $.ajax({
                    type: "get",
                    url: "/cms.php/module/makecontrollerphp.html",
                    data: {name:sname},
                    success: function (datas) {
                        Layer.alert('生成完毕');
                    },
                    error: function () {
                        Layer.alert('生成失败');
                    },
                    complete: function () {

                    }
                });
            });
            $("#mcm").click(function(){
                var sname = $("#c-enname").val();
                var itemid = $(this).data('id');
                $.ajax({
                    type: "get",
                    url: "/cms.php/module/makemodelphp",
                    data: {name:sname,itemid:itemid},
                    success: function (datas) {
                        Layer.alert('生成完毕');
                    },
                    error: function () {
                        Layer.alert('生成失败');
                    },
                    complete: function () {

                    }
                });
            });
            //开启
            $("#mopen").click(function(){
                var sname = $("#c-enname").val();
                $.ajax({
                    type: "get",
                    url: "/cms.php/module/open.html",
                    data: {name:sname},
                    success: function (datas) {
                        Layer.alert('开启完毕');
                    },
                    error: function () {
                        Layer.alert('开启失败');
                    },
                    complete: function () {

                    }
                });
            });
            //关闭
            $("#mclose").click(function(){
                var sname = $("#c-enname").val();
                $.ajax({
                    type: "get",
                    url: "/cms.php/module/close.html",
                    data: {name:sname},
                    success: function (datas) {
                        Layer.alert('关闭完毕');
                    },
                    error: function () {
                        Layer.alert('关闭失败');
                    },
                    complete: function () {

                    }
                });
            });
            //生成数据表
            $("#msql").click(function(){
                var sname = $("#c-enname").val();
                $.ajax({
                    type: "get",
                    url: "/cms.php/module/makesql.html",
                    data: {name:sname},
                    success: function (datas) {
                        Layer.alert('生成完毕');
                    },
                    error: function () {
                        Layer.alert('生成失败');
                    },
                    complete: function () {

                    }
                });
            });
            $(".returnback").click(function(){
                history.back();
            });
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
function creatList(obj, list){
		$.each(eval(obj), function(i,item) {
				var temp = new Object();
				temp.text = item.name;
				temp.value = item.id;
				list.push(temp);
		});
}
//补足表格的列(PC)
function addColumnPc(key){
		var l = 10000;//初始化顺序
		var columnenname = '';var columnname = '';
		$.each(eval(pagedata.columns),function(k,v){
				var temp = new Object();
				if(k.toLowerCase()==key){
						columnenname = v.columnenname;
						columnname = v.columnname;
						l = v.listorder;
				}
				if((v.listorder>l)&&(v.isshowlist==1)){
						var html = "";
						$("#table thead").find("tr th[data-field='"+v.columnenname+"']").before('<th data-field="'+columnenname+'"><div class="th-inner">'+columnname+'</div><div class="fht-cell"></div></th>');
						var list = eval(pagedata.list);
						var cv = '';
						var lst = $("#table tbody tr").find("td[columnname="+Fast.api.ucfirst(v.columnenname)+"]");
						//把单元格的列加上
						lst.each(function(i){
								$(this).before('<td columnname="'+Fast.api.ucfirst(columnenname)+'">'+list[i][columnenname.toLowerCase()]+'</td>');
						});
						return false;
				}
		});
}
//补足表格的列(Mobile)
function addColumnMobile(key){
		var l = 10000;//初始化顺序
		var columnenname = '';var columnname = '';
		$.each(eval(pagedata.columns),function(k,v){
				var temp = new Object();
				if(k.toLowerCase()==key){
						columnenname = v.columnenname;
						columnname = v.columnname;
						l = v.listorder;
				}
				if((v.listorder>l)&&(v.isshowlist==1)){
						var html = "";
						var list = eval(pagedata.list);
						var cv = '';
						var lst = $("#datalist tr td").find("div[columnname="+v.columnenname+"]");
						//把单元格的列加上
						lst.each(function(i){
								$(this).before('<div class="card-view" columnname="'+columnenname.toLowerCase()+'"><span class="title">'+columnname+'</span><span class="value">'+list[i][columnenname.toLowerCase()]+'</span></div>');
						});return false;
				}
		});
		return false;
}
